package com.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.StringTool;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.RoleVo;
import com.app.vo.TestsVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/tests")
public class TestsController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private TestsService testsService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PersonService personService;
    @Autowired
    private TestsPersonService testsPersonService;

    @GetMapping("/getDropList")//下拉框查询
    public Result<Object> getDropList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryVo vo = new CategoryVo();
        List<CategoryModel> categoryModelList = categoryService.getCategoryByPid(21);//实验类型
        vo.setTestTypeList(categoryModelList);
        List<CategoryModel> categoryModelList1 = categoryService.getCategoryByPid(22);//实验科目
        vo.setSubjectList(categoryModelList1);
        List<CategoryModel> categoryModelList2 = categoryService.getCategoryByPid(24);//排故周期
        vo.setPeriodList(categoryModelList2);
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        List<PersonModel> personList = personService.otherPersonList(idList);
        if (personList != null && personList.size() > 0) {
            vo.setPersonList(personList);
        }
        List<TypeModel> typeModelList = typeService.getTypeList(idList);
        vo.setTypeModelList(typeModelList);
        return Result.success(vo);
    }

    @GetMapping("/getTestsList")//实验管理分页查询
    public Result<Object> getTestsList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) String breakdowns,
            @RequestParam(required = false) Integer modelType,
            @RequestParam(required = false) Integer departmentId,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());

        Page<TestsModel> testsModelPage = testsService.getPageTestsList(page, limit, name, modelType, breakdowns, idList, year,departmentId);
        for (int i = 0; i < testsModelPage.getRecords().size(); i++) {
            if (testsModelPage.getRecords().get(i).getFileUrl() != null) {
                String fileUrl = testsModelPage.getRecords().get(i).getFileUrl();
                String replace = fileUrl.replace("[", "");
                String newFileUrl = replace.replace("]", "");
                String[] split = newFileUrl.split(",");
                testsModelPage.getRecords().get(i).setFileUrlArr(split);
            }
            if (testsModelPage.getRecords().get(i).getDepartmentId() != null) {
                DepartmentModel departmentModel = departmentService.getDepByDepId(testsModelPage.getRecords().get(i).getDepartmentId());//部门
                if (departmentModel != null) {
                    testsModelPage.getRecords().get(i).setDepartmentName(departmentModel.getName());
                }
            }
            testsModelPage.getRecords().get(i).setTimeRange(testsModelPage.getRecords().get(i).getStartTime() + " 至 " + testsModelPage.getRecords().get(i).getEndTime());
            if (testsModelPage.getRecords().get(i).getId() != null) {
                List<TestsPersonModel> personModelList = testsPersonService.getTestsPersonList(testsModelPage.getRecords().get(i).getId());
                if (personModelList.size() > 0) {
                    testsModelPage.getRecords().get(i).setPersonList(personModelList);
                    for (int j = 0; j < personModelList.size(); j++) {
                        personModelList.get(j).setTimeRange(personModelList.get(j).getStartTime() + " " + "--" + " " + personModelList.get(j).getEndTime());
                        PersonModel personModel = personService.selectPersonById(personModelList.get(j).getPersonId());
                        personModelList.get(j).setPersonName(personModel.getName());
                    }
                }
            }
        }
        if (testsModelPage.getRecords() == null) {
            return Result.error(200, "暂无数据");
        }
        int count = (int) testsModelPage.getTotal();
        List<TestsModel> testsModelList;
        testsModelList = testsModelPage.getRecords();
        TestsVo vo = new TestsVo();
        vo.setCount(count);
        vo.setList(testsModelList);
        return Result.success(vo);
    }

    @PostMapping("/insertTests")//    新增/修改实验管理
    public Result<Object> insertRole(
            @RequestBody JSONObject json,
            HttpServletRequest request) {
        TestsModel testsModel = new TestsModel();
        Integer id = Integer.valueOf(json.get("id").toString());
        Integer departmentId = Integer.valueOf(json.get("departmentId").toString());
        String name = json.get("name").toString();
        String testType = json.get("testType").toString();
        Integer year = Integer.valueOf(json.get("year").toString());
        String modelType = json.get("modelType").toString();
        String subject = json.get("subject").toString();
        String startTime = json.get("startTime").toString();
        String endTime = json.get("endTime").toString();
        if (json.containsKey("description") && json.get("description") != null) {
            String description = json.get("description").toString();
            testsModel.setDescription(description);
        }
        if (json.containsKey("errorLog") && json.get("errorLog") != null) {
            String errorLog = json.get("errorLog").toString();
            testsModel.setErrorLog(errorLog);
        }
        if (json.containsKey("fileUrl")) {
            String fileUrl = json.get("fileUrl").toString();
            if (fileUrl.equals("[]")) {
                testsModel.setFileUrl(null);
            } else {
                testsModel.setFileUrl(fileUrl);
            }
        }

        String personRemove = json.get("personRemove").toString();// 需要删除的负责人ID数组

        //编辑中新增的简历
        String personAdd = JSON.toJSON(json.get("personAdd")).toString();
        List<TestsPersonModel> personAddList = JSON.parseArray(personAdd, TestsPersonModel.class);

        //编辑中更改的简历
        String personEdit = JSON.toJSON(json.get("personEdit")).toString();// 新增的职务
        List<TestsPersonModel> personEditList = JSON.parseArray(personEdit, TestsPersonModel.class);

        List<TestsPersonModel> personList = new ArrayList<>();
        if (json.get("personList") != null && json.get("personList").toString().length() > 0) {
            String resumeJson = JSON.toJSON(json.get("personList")).toString();
            personList = JSONObject.parseArray(resumeJson, TestsPersonModel.class);
        }

        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        testsModel.setDepartmentId(departmentId);
        testsModel.setName(name);
        testsModel.setTestType(testType);
        testsModel.setYear(year);
        testsModel.setModelType(modelType);
        testsModel.setSubject(subject);
        testsModel.setStartTime(startTime);
        testsModel.setEndTime(endTime);
        try {
            if (id > 0) {
                testsModel.setId(id);
                testsModel.setUpdateTime(CommonHelp.getNowTimestamp());
                testsService.update(testsModel);
                if (StringTool.isNotEmpty(personRemove)) {
                    String[] positionRemoveArr = personRemove.split(",");
                    System.out.println("第一次打印" + positionRemoveArr);
                    for (int i = 0; i < positionRemoveArr.length; i++) {
                        testsPersonService.delete(Integer.parseInt(positionRemoveArr[i]));
                    }
                }
                if (personAddList.size() > 0) {
                    for (int i = 0; i < personAddList.size(); i++) {
                        TestsPersonModel personModel = new TestsPersonModel();
                        personModel.setTestsId(testsModel.getId());
                        personModel.setPersonId(personAddList.get(i).getPersonId());
                        personModel.setContent(personAddList.get(i).getContent());
                        personModel.setStartTime(personAddList.get(i).getStartTime());
                        personModel.setEndTime(personAddList.get(i).getEndTime());
                        personModel.setCreateTime(CommonHelp.getNowTimestamp());
                        testsPersonService.insert(personModel);
                    }
                }
                if (personEditList.size() > 0) {
                    for (TestsPersonModel testsPersonModel : personEditList) {//有ID
                        TestsPersonModel personModel = new TestsPersonModel();
                        personModel.setId(testsPersonModel.getId());
                        personModel.setTestsId(testsModel.getId());
                        personModel.setPersonId(testsPersonModel.getPersonId());
                        personModel.setContent(testsPersonModel.getContent());
                        personModel.setStartTime(testsPersonModel.getStartTime());
                        personModel.setEndTime(testsPersonModel.getEndTime());
                        personModel.setUpdateTime(CommonHelp.getNowTimestamp());
                        testsPersonService.update(personModel);
                    }
                }

            } else {
                testsModel.setCreateTime(CommonHelp.getNowTimestamp());
                testsService.insert(testsModel);
                if (personList.size() > 0) {
                    for (int i = 0; i < personList.size(); i++) {
                        TestsPersonModel personModel = new TestsPersonModel();
                        personModel.setTestsId(testsModel.getId());
                        personModel.setPersonId(personList.get(i).getPersonId());
                        personModel.setContent(personList.get(i).getContent());
                        personModel.setStartTime(personList.get(i).getStartTime());
                        personModel.setEndTime(personList.get(i).getEndTime());
                        personModel.setCreateTime(CommonHelp.getNowTimestamp());
                        testsPersonService.insert(personModel);
                    }

                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success(null);
    }

    @GetMapping("/deleteById")//删除实验
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        TestsModel testsModel = testsService.getTestById(id);
        if (testsModel == null) {
            return Result.error(500, "该角色不存在");
        } else {
            testsService.delete(id);
            return Result.success(null);
        }
    }
    /**
     * 批量删除实验数据
     * @param ids
     * @param request
     * @return
     */
    @DeleteMapping("/deleteBatchByIds")
    public Result<Object> deleteBatchById(@RequestParam("ids") String ids, HttpServletRequest request) {
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        // 执行批量删除操作
        return testsService.deleteBatchByIds(ids);
    }

    // 校验token并获取用户信息的方法
    private AdminUserModel validateTokenAndGetUser(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            throw new IllegalArgumentException("token不存在");
        }
        String userId = TokenUtils.verify(token);
        return adminUserService.getUserByUserId(Integer.parseInt(userId));
    }
}
